<template>
  <div class="adoption-form">
    <div class="container">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <div v-else-if="!pet" class="error-container">
        <el-empty description="未找到宠物信息" />
        <el-button @click="$router.push('/pets')" type="primary" class="mt-3">
          返回宠物列表
        </el-button>
      </div>
      
      <template v-else>
        <div class="back-link mb-3">
          <router-link :to="'/pets/' + id">
            <i class="el-icon-arrow-left"></i> 返回宠物详情
          </router-link>
        </div>
        
        <h2 class="page-title">申请领养 {{ pet.name }}</h2>
        
        <div class="form-container">
          <el-row :gutter="20">
            <el-col :md="8" :sm="24">
              <div class="pet-summary">
                <div class="pet-image-container">
                  <img :src="petImageUrl" :alt="pet.name" class="pet-image">
                </div>
                <h3 class="pet-name">{{ pet.name }}</h3>
                <div class="pet-meta">
                  <div class="meta-item">
                    <span class="meta-label">类别:</span>
                    <span class="meta-value">{{ getCategoryName(pet.category_id) }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">品种:</span>
                    <span class="meta-value">{{ pet.breed || '未知' }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">性别:</span>
                    <span class="meta-value">{{ formatGender(pet.gender) }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="meta-label">年龄:</span>
                    <span class="meta-value">{{ formatAge(pet.age) }}</span>
                  </div>
                </div>
              </div>
            </el-col>
            
            <el-col :md="16" :sm="24">
              <div class="application-form">
                <el-form 
                  ref="applicationForm" 
                  :model="formData" 
                  :rules="rules" 
                  label-position="top"
                >
                  <h3>领养意向</h3>
                  
                  <el-form-item label="申请领养的理由" prop="reason_for_adoption">
                    <el-input 
                      type="textarea" 
                      v-model="formData.reason_for_adoption" 
                      rows="4"
                      placeholder="请详细描述您想要领养这只宠物的原因"
                    ></el-input>
                  </el-form-item>
                  
                  <h3>居住情况</h3>
                  
                  <el-form-item label="居住环境描述" prop="living_situation">
                    <el-input 
                      type="textarea" 
                      v-model="formData.living_situation" 
                      rows="4"
                      placeholder="请详细描述您的居住环境（如住房类型、面积、是否有院子等）"
                    ></el-input>
                  </el-form-item>
                  
                  <h3>养宠经验</h3>
                  
                  <el-form-item label="您以前的养宠经验" prop="previous_pet_experience">
                    <el-input 
                      type="textarea" 
                      v-model="formData.previous_pet_experience" 
                      rows="4"
                      placeholder="如有养宠经验，请描述；如无经验可以留空"
                    ></el-input>
                  </el-form-item>
                  
                  <el-form-item label="其他补充信息" prop="additional_notes">
                    <el-input 
                      type="textarea" 
                      v-model="formData.additional_notes" 
                      rows="4"
                      placeholder="其他您想补充的信息（可选）"
                    ></el-input>
                  </el-form-item>
                  
                  <el-form-item prop="agree_terms">
                    <el-checkbox v-model="formData.agree_terms">
                      我已阅读并同意《宠物领养协议》，保证所填信息真实有效，并承诺善待宠物，不遗弃，不虐待
                    </el-checkbox>
                  </el-form-item>
                  
                  <!-- 提交按钮 -->
                  <div class="form-actions">
                    <button 
                      type="button" 
                      class="submit-btn"
                      :disabled="submitting"
                      @click="handleSubmit"
                    >
                      {{ submitting ? '提交中...' : '提交申请' }}
                    </button>
                    
                    <button type="button" class="cancel-btn" @click="$router.push('/pets')">
                      取消
                    </button>
                  </div>
                </el-form>
              </div>
            </el-col>
          </el-row>
        </div>
      </template>
      
      <!-- 申请已存在提示对话框 -->
      <el-dialog
        title="提示"
        v-model="duplicateDialogVisible"
        width="30%"
        center
      >
        <div class="duplicate-dialog-content">
          <p>您已经为这只宠物提交了申请，该申请正在等待审核。</p>
          <p>在当前申请审核完成前，无法再次提交申请。</p>
          <p>您可以在"我的申请"中查看申请状态。</p>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="goToMyApplications">查看我的申请</el-button>
            <el-button @click="duplicateDialogVisible = false">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import axios from 'axios';

export default {
  name: 'AdoptionForm',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      submitting: false,
      duplicateDialogVisible: false,
      formData: {
        reason_for_adoption: '',
        living_situation: '',
        previous_pet_experience: '',
        additional_notes: '',
        agree_terms: false
      },
      rules: {
        reason_for_adoption: [
          { required: true, message: '请说明领养理由', trigger: 'blur' },
          { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
        ],
        living_situation: [
          { required: true, message: '请描述您的居住环境', trigger: 'blur' },
          { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
        ],
        previous_pet_experience: [
          { max: 500, message: '长度不超过 500 个字符', trigger: 'blur' }
        ],
        additional_notes: [
          { max: 500, message: '长度不超过 500 个字符', trigger: 'blur' }
        ],
        agree_terms: [
          { 
            required: true, 
            message: '请阅读并同意领养协议', 
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请阅读并同意领养协议'));
              } else {
                callback();
              }
            } 
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      pet: 'pets/getPet',
      categories: 'categories/allCategories',
      loading: 'isLoading',
      user: 'auth/currentUser'
    }),
    petImageUrl() {
      if (!this.pet || !this.pet.image_url) {
        return 'https://via.placeholder.com/300x300?text=No+Image';
      }
      
      const apiUrl = process.env.VUE_APP_API_URL || 'http://localhost:3000';
      return this.pet.image_url.startsWith('http') 
        ? this.pet.image_url 
        : `${apiUrl}${this.pet.image_url}`;
    }
  },
  async created() {
    try {
    if (this.categories.length === 0) {
      await this.fetchCategories();
    }
    
    await this.fetchPet(this.id);
    
    if (this.user) {
        this.formData.reason_for_adoption = this.user.reason_for_adoption || '';
        this.formData.living_situation = this.user.living_situation || '';
        this.formData.previous_pet_experience = this.user.previous_pet_experience || '';
        this.formData.additional_notes = this.user.additional_notes || '';
      }
    } catch (error) {
      console.error('初始化数据失败:', error);
      this.$message.error('加载数据失败，请刷新页面重试');
    }
  },
  methods: {
    ...mapActions({
      fetchPet: 'pets/fetchPet',
      fetchCategories: 'categories/fetchCategories'
    }),
    formatGender(gender) {
      const genderMap = {
        'male': '公',
        'female': '母',
        'unknown': '未知'
      };
      return genderMap[gender] || '未知';
    },
    formatAge(age) {
      if (!age) return '未知';
      return `${age} 岁`;
    },
    getCategoryName(categoryId) {
      if (!categoryId) return '未知';
      const category = this.categories.find(c => c.id === categoryId);
      return category ? category.name : '未知';
    },
    validateForm() {
      return new Promise((resolve) => {
        this.$refs.applicationForm.validate((valid) => {
          resolve(valid);
        });
      });
    },
    async handleSubmit() {
      console.log('开始提交表单');
      
      // 检查登录状态
      if (!this.user || !this.user.id) {
        this.$message.error('请先登录后再申请领养');
        return;
      }
      
      // 表单验证
      const isValid = await this.validateForm();
      if (!isValid) {
        this.$message.warning('请完善所有必填信息后再提交');
        return;
      }
      
      // 检查是否已有待审核的申请
      if (await this.checkExistingApplication()) {
        return;
      }
      
      // 设置提交状态
        this.submitting = true;
        
      // 获取认证令牌
      const token = localStorage.getItem('token') || '';
      const apiUrl = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';
      
      try {
        // 准备提交数据
        const formData = {
          user_id: this.user.id,
          pet_id: parseInt(this.id, 10),
          reason_for_adoption: this.formData.reason_for_adoption,
          living_situation: this.formData.living_situation,
          previous_pet_experience: this.formData.previous_pet_experience || '',
          additional_notes: this.formData.additional_notes || '',
          application_date: new Date().toISOString(),
          status: 'pending'
        };
        
        console.log('提交数据:', formData);
        
        // 尝试多种可能的API格式 - 找出正确的一个
        const possibleUrls = [
          'http://localhost:3000/api/adoptions/apply',
          'http://localhost:3000/adoptions/apply',
          'http://localhost:3000/api/adoption/apply',
          '/api/adoptions/apply'
        ];
        
        let success = false;
        let response = null;
        let lastError = null;
        
        // 尝试每一个可能的URL
        for (const url of possibleUrls) {
          try {
            console.log(`尝试请求URL: ${url}`);
            
            response = await axios.post(url, formData, {
              headers: {
                'Content-Type': 'application/json',
                'x-auth-token': token
              }
            });
            
            // 如果请求成功
            console.log(`URL ${url} 请求成功!`);
            success = true;
            break;
          } catch (err) {
            console.log(`URL ${url} 请求失败:`, err.message);
            // 检查是否是重复提交导致的错误
            if (err.response && err.response.data && 
                err.response.data.message) {
              console.log('后端错误消息:', err.response.data.message);
              
              // 检查是否与待审核申请相关
              if (err.response.data.message.includes('Duplicate entry') || 
                  err.response.data.message.includes('already have a pending application') ||
                  err.response.data.message.includes('pending application')) {
                this.showDuplicateDialog();
                this.submitting = false;
                return;
              }
            }
            lastError = err;
            // 继续尝试下一个URL
          }
        }
        
        // 检查是否有一个URL成功
        if (success && response) {
          console.log('提交成功, 响应:', response.data);
          
          // 显示成功消息
          this.$message.success('申请已提交成功！我们会尽快审核您的申请。');
          
          // 跳转到宠物列表页面
          window.location.href = '/pets';
        } else {
          // 所有URL都失败了
          throw lastError || new Error('所有API路径都请求失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        
        // 检查是否是重复提交导致的错误
        if (error.response && error.response.data && 
            error.response.data.message) {
          console.log('后端错误消息:', error.response.data.message);
            
          // 检查是否与待审核申请相关
          if (error.response.data.message.includes('Duplicate entry') || 
              error.response.data.message.includes('already have a pending application') ||
              error.response.data.message.includes('pending application')) {
            this.showDuplicateDialog();
            return; // 提前返回，不显示其他错误消息
          }
        } else {
          // 尝试直接发送到后端根路径查看是否可访问
          try {
            await axios.get('http://localhost:3000/');
            console.log('后端服务器可访问');
          } catch (e) {
            console.error('后端服务器不可访问，可能已关闭:', e.message);
          }
          
          // 提示用户
          if (error.response?.status === 404) {
            this.$message.error('提交失败: API路径不存在，请检查后端服务是否正常运行');
          } else {
            this.$message.error('提交申请失败: ' + (error.response?.data?.message || error.message || '请稍后重试'));
          }
        }
      } finally {
        this.submitting = false;
      }
    },
    
    // 检查是否已有申请
    async checkExistingApplication() {
      console.log('检查是否已有待审核的申请');
      
      try {
        const token = localStorage.getItem('token') || '';
        const apiUrl = process.env.VUE_APP_API_URL || 'http://localhost:3000/api';
        
        // 尝试不同的API路径
        const possibleUrls = [
          `${apiUrl}/adoptions/my-applications`,
          `${apiUrl.replace('/api', '')}/api/adoptions/my-applications`,
          `${apiUrl.replace('/api', '')}/adoptions/my-applications`
        ];
        
        let existingApplications = [];
        let success = false;
        
        for (const url of possibleUrls) {
          try {
            console.log(`检查申请，尝试URL: ${url}`);
            const response = await axios.get(url, {
              headers: {
                'x-auth-token': token
              }
            });
            
            if (response.data && (Array.isArray(response.data) || response.data.applications)) {
              existingApplications = Array.isArray(response.data) ? response.data : response.data.applications;
              success = true;
              console.log('获取到现有申请:', existingApplications);
              break;
            }
          } catch (err) {
            console.log(`URL ${url} 请求失败:`, err.message);
          }
        }
        
        if (!success) {
          console.log('无法获取现有申请，将继续提交');
          return false;
        }
        
        const currentPetId = parseInt(this.id, 10);
        console.log('当前宠物ID:', currentPetId, '(类型:', typeof currentPetId, ')');
        
        // 筛选当前宠物的申请并打印详细信息
        const petApplications = existingApplications.filter(app => {
          const appPetId = typeof app.pet_id === 'string' ? parseInt(app.pet_id, 10) : app.pet_id;
          console.log('比较申请ID:', appPetId, '(类型:', typeof appPetId, ') 与当前ID:', currentPetId, '结果:', appPetId === currentPetId);
          return appPetId === currentPetId;
        });
        
        console.log('当前宠物的申请:', petApplications);
        
        // 检查是否有待审核状态的申请
        const pendingApplications = petApplications.filter(app => app.status === 'pending');
        console.log('待审核的申请:', pendingApplications);
        
        const hasPendingApplication = pendingApplications.length > 0;
        
        if (hasPendingApplication) {
          console.log('发现待审核的申请，禁止重复提交');
          this.showDuplicateDialog();
          return true;
        }
        
        // 如果没有待审核申请，但有其他状态的申请（如已拒绝），允许重新申请
        const hasOtherApplication = petApplications.length > 0;
        if (hasOtherApplication) {
          console.log('发现其他状态的申请，允许重新提交');
          
          // 对于已拒绝的申请，显示提示但允许继续
          const hasRejectedApplication = petApplications.some(app => app.status === 'rejected');
          if (hasRejectedApplication) {
            this.$message.info('您之前的申请已被拒绝，您可以重新提交申请。');
          }
        }
        
        return false; // 允许提交申请
        
      } catch (error) {
        console.error('检查现有申请失败:', error);
        return false; // 检查失败时继续提交
      }
    },
    
    // 显示重复申请对话框
    showDuplicateDialog() {
      this.duplicateDialogVisible = true;
    },
    
    // 跳转到我的申请页面
    goToMyApplications() {
      this.duplicateDialogVisible = false;
      this.$router.push('/my-applications');
    }
  }
};
</script>

<style lang="scss" scoped>
.adoption-form {
  padding: 40px 0;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
  padding: 30px;
}

.back-link a {
  color: var(--primary-color, #409EFF);
    display: inline-flex;
    align-items: center;
    
    i {
      margin-right: 5px;
  }
}

.page-title {
  margin-bottom: 25px;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
}

.pet-summary {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 20px;
}

.pet-image-container {
  margin-bottom: 15px;
}

.pet-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.pet-name {
  font-size: 1.5rem;
  margin: 15px 0;
  color: var(--secondary-color, #6c757d);
  text-align: center;
}

.pet-meta {
  .meta-item {
    display: flex;
    margin-bottom: 8px;
  }
  
  .meta-label {
    font-weight: bold;
    width: 60px;
    color: #6c757d;
  }
  
  .meta-value {
    flex-grow: 1;
  }
}

.application-form {
  h3 {
    color: var(--secondary-color, #6c757d);
    margin: 25px 0 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }
  
  h3:first-child {
    margin-top: 0;
  }
}

.form-actions {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

/* 原生按钮样式 */
.submit-btn {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  
  &:hover {
    background-color: #66b1ff;
  }
  
  &:disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
  }
}

.cancel-btn {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    color: #409EFF;
    border-color: #c6e2ff;
    background-color: #ecf5ff;
  }
}

@media (max-width: 768px) {
  .pet-summary {
    position: static;
    margin-bottom: 20px;
  }
  
  .form-actions {
    flex-direction: column;
    
    .submit-btn,
    .cancel-btn {
      width: 100%;
      margin-bottom: 10px;
    }
  }
}

.duplicate-dialog-content {
  text-align: center;
  padding: 20px 0;
  
  p {
    margin: 10px 0;
    font-size: 16px;
    color: #333;
  }
}
</style> 